import axios from 'axios'
import {Loading, Message, MessageBox} from 'element-ui'
import router from "@/router"
import {isEmpty} from "@/utils/util";

// loading实例
let loadingInstance

// 更换令牌的时间区间
const checkRegion = 5 * 60 * 1000
// 提示信息显示时长
const messageDuration = 5 * 1000

function endLoading() {
  loadingInstance && loadingInstance.close()
}

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'Access-Control-Allow-Origin': '*'
  },
  timeout: 50000,
  responseType: 'json',
})

// 请求拦截
service.interceptors.request.use(
  config => {

    // 在请求发送之前显示loading
    loadingInstance = Loading.service({
      lock: true,
      text: '加载中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    return config
  },
  error => {
    // 关闭loading
    loadingInstance && loadingInstance.close()
    console.error('请求错误：', error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(response => {
    // 关闭loading
    loadingInstance && loadingInstance.close()

    return response.data
  },
  error => {
    endLoading()
    if (error.response) {
      const errorMessage = error.response.data === null ? '系统内部异常，请联系网站管理员' : error.response.data.message

      switch (error.response.status) {
        case 404:
          Message({
            message: '很抱歉，资源未找到',
            type: 'error',
            duration: messageDuration
          })
          break
        case 403:
          Message({
            message: '很抱歉，您暂无该操作权限',
            type: 'error',
            duration: messageDuration
          })
          break
        case 401:
          Message({
            message: '很抱歉，认证已失效，请重新登录',
            type: 'error',
            duration: messageDuration
          })
          break
        default:
          if (errorMessage === 'refresh token无效') {
            MessageBox.alert('登录已过期，请重新登录', '温馨提示', {
              confirmButtonText: '确定',
              showClose: false,
              callback: action => {
                router.push('/login')
              }
            })
          } else if (errorMessage === 'Request processing failed; nested exception is org.springframework.security.authentication.InternalAuthenticationServiceException: manager is null') {
            Message({
              message: '当前账号经理未配置菜单,请配置菜单!',
              type: 'error',
              duration: messageDuration
            })
          } else if (errorMessage === 'Request processing failed; nested exception is error="invalid_grant", error_description="Bad credentials"') {
            Message({
              message: '用户名或密码错误!',
              type: 'error',
              duration: messageDuration
            })
          } else if (errorMessage === 'No message available') {
            Message({
              message: '登录超期，请重新登录。',
              type: 'error',
              duration: messageDuration
            })

            setTimeout(router.push('/login'), "4000");
          } else {
            Message({
              message: errorMessage,
              type: 'error',
              duration: messageDuration
            })
          }
          break
      }
    }
    return Promise.reject(error)
  }
)


export default service
